package com.example.aesdemo.interceptor;

import com.example.aesdemo.util.AesUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Array;
import java.util.Map;

/**
 * @description: data
 * @author: Mr.Hu
 * @create: 2018-05-31 11:47
 **/
@Component
public class DataEncryptionInterceptor implements HandlerInterceptor {

    @Autowired
    private AesUtil aesUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map map = request.getParameterMap();

        System.out.println(map.size());
        map.forEach((key, obj)->{
                System.out.println(key+":"+ Array.get(obj,0));
                String value = (String)Array.get(obj,0);
                if(value.startsWith("**ENCRYPT**")){
                    String salt = value.substring(11,43);
                    String iv = value.substring(43, 75);
                    String ciphertext = value.substring(75, value.length());
                    String jsonStr = aesUtil.decrypt(salt, iv, ciphertext);
                    
                }

        }
        );
        if (map.containsKey("salt")&&map.containsKey("iv")&&map.containsKey("ciphertext")){
            String salt = (String) Array.get(map.get("salt"),0);
            String iv = (String) Array.get(map.get("iv"),0);
            String ciphertext = (String) Array.get(map.get("ciphertext"),0);
            String jsonStr = aesUtil.decrypt(salt, iv, ciphertext);
            System.out.println(jsonStr);
        }

        return true;
    }
}
